<template>
  <a-modal
    :title="model && model.id > 0 ? '编辑' : '新增'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout" >
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="关键词">
          <a-input
            placeholder="请输入关键词"
            v-decorator="['keyWord', {rules: [{required: true, message: '请输入关键词'}]}]" />
        </a-form-item>
        <a-form-item label="回复内容">
          <a-textarea
            placeholder="请输入回复内容"
            :rows="4"
            v-decorator="['replyContent', {rules: [{required: true, message: '请输入回复内容'}]}]"></a-textarea>
        </a-form-item>
        <a-form-item label="附件">
          <a-upload
            accept=".pdf,.docx,.doc,image/png, image/jpeg"
            name="file"
            action="/grade-evaluation-api/minio/uploadFile"
            :headers="headers"
            :before-upload="beforeAnnexUpload"
            v-decorator="[
              'fileList',
              {
                rules: [{required: false, message: '请上传附件'}],
                valuePropName: 'fileList',
                getValueFromEvent: normImg,
              },
            ]"
          >
            <a-button icon="upload">点击上传</a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 表单字段
const fields = ['id', 'keyWord', 'replyContent', 'fileList']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
      headers: {
        Authorization: storage.get(ACCESS_TOKEN)
      }
    }
  },
  created () {
    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    beforeAnnexUpload (file) {
      const fileType = file.name.split('.')
      const fileFormat = fileType.slice(-1)
      const isPdfOrWord = ['doc', 'docx', 'pdf'].indexOf(fileFormat[0]) > -1
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!(isPdfOrWord || isJpgOrPng)) {
        this.$message.error('只能上传图片，word和pdf格式!')
      }
      return isPdfOrWord || isJpgOrPng
    },
    normImg (e) {
      console.log('Upload img event:', e)
      if (e.fileList.length > 1) {
          // 限制只上传一个文件，再次上传时则替换(覆盖)以前的文件
          // splic(0,1)是把第一个删除
          e.fileList.splice(0, 1)
      }
      if (e.file.status === 'uploading') {
        return e.fileList
      }
      if (e.file.status === 'done') {
        const list = []
        e.fileList.forEach(item => {
          if (item.response) {
            const { id, original, url } = item.response.data
            list.push({
              uid: id,
              name: original,
              status: 'done',
              url: url
            })
          } else {
            list.push(item)
          }
        })
        return list
      }
    }
  }
}
</script>
